<template>
  <div class="dashboard-container">
    <el-row style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px">
      <span v-html="dateValue" /><span class="line___3lQ2g" />
      <div id="icon" style="display:inline"><img id="wicon" :src="'http://openweathermap.org/img/w/'+content+'.png'" alt="Weather icon"></div>
      <span class="weather" v-html="weatherValue"><i class="icon iconfont iconqingtian1" /></span>
      <!-- <el-tooltip class="item" effect="light" :content="content" transition="true" placement="top-end"> -->
      <!-- <el-button class="weatherTip">温馨提示</el-button> -->
      <!-- </el-tooltip> -->
      <input
        id="startAddress"
        type="text"
        placeholder="经度"
        style="width: 10em"
        @keyup.enter="search"
      >
      <input
        id="endAddress"
        type="text"
        placeholder="维度"
        style="width: 10em"
        @keyup.enter="search"
      >
      <input type="button" value="搜索" @click="search">
      <input type="button" value="路线" @click="routePoints">
      <input type="button" value="暂停" @click="reset">
      <!-- 检索地址容器 -->
      <!-- <div id="r-result" style="float: left; margin-top: -370px"> -->
      <el-input
        id="suggestId"
        v-model="city"
        style="width: 350px"
        size="mini"
        type="text"
      >
        <template slot="prepend">请输入：</template>
      </el-input>
      <div id="r-result" style="position: fixed; top: 100px; right: 5px" />
      <!-- </div> -->
      <!-- <el-input v-model="city">城市</el-input> -->
      <!-- 具体地点
      <el-select
        v-model="place"
        filterable
        remote
        reserve-keyword
        placeholder="请输入关键词"
        :remote-method="remoteMethod"
        :loading="loading"
        @change="getSearchPoint(place)"
      >

        <el-option
          v-for="item in restaurants"
          :key="item.uid"
          :label="item.title"
          :value="item"
        />
      </el-select> -->

      <baidu-map
        :center="center"
        :zoom="zoom"
        style="height: 1080px"
        :scroll-wheel-zoom="true"
        @ready="handler"
        @click="getClickInfo"
      >
        <bm-panorama />
        <bml-marker-clusterer :average-center="true">
          <bm-marker v-for="marker of markers" :key="marker" :position="{lng: marker.lng, lat: marker.lat}" />
        </bml-marker-clusterer>
        <!-- 运行轨迹的路线 -->
        <bm-polyline
          stroke-color="blue"
          :path="path"
          :stroke-opacity="0.5"
          :stroke-weight="3"
          :editing="false"
        />
        <!-- marker 可以展示的图标 起点、终点 -->
        <bm-marker
          :icon="startMarkIcon"
          :position="{ lng: startMark.lng, lat: startMark.lat }"
        />
        <bm-marker
          :icon="endMarkIcon"
          :position="{ lng: endMark.lng, lat: endMark.lat }"
        />
        <bml-lushu
          :path="path"
          :icon="icon"
          :play="play"
          :rotation="true"
          :speed="100"
          @stop="reset"
        />
        <bm-local-search
          :keyword="place"
          :auto-viewport="true"
          class="search"
          @searchcomplete="search"
        />
      </baidu-map>
    </el-row>
    <el-row>
      <imageVue />
    </el-row>

  </div>
</template>
<script type="text/javascript" src="//api.map.baidu.com/library/TrackAnimation/src/TrackAnimation_min.js"></script>
<script>
var point;
var polyline;
import crudScenic from '@/api/scenic'
import imageVue from '@/views/map/basicMap/image.vue'
import startPoint from "@/assets/images/startPoint.png";
import endPoint from "@/assets/images/endPoint.png";
import {BmlMarkerClusterer} from 'vue-baidu-map'

import { getAllRoutePoint } from "@/api/routePont";
import screenfull from "screenfull";
import { BmlLushu, BmLocalSearch } from "vue-baidu-map";
export default {
  name: "Dashboard",
  components: {
    imageVue,
    BmlLushu,
    BmLocalSearch,
    BmlMarkerClusterer
  },
  data() {

    return {
      markers:[],
      maker: null,
      circle: null,
      loading: false,
      city: null,
      place: null,
      lng: 112.848085,
      point: null,
      lat: 35.494521,
      center: { lng: this.lng, lat: this.lat },
      zoom: 13,
      dateValue: null,
      weatherValue: null,
      content: null,
      map: null,
      BMap: null,
      routes: [],
      msg_data: [],
      list: [],
      icon: {
        url: "http://api.map.baidu.com/library/LuShu/1.2/examples/car.png",
        size: {
          width: 52,
          height: 52,
        },
        opts: {
          anchor: {
            width: 26,
            height: 26,
          },
        },
      },
      startMark: {}, //起点
      startMarkIcon: {
        url: startPoint,
        size: {
          width: 52,
          height: 52,
        },
        opts: {
          anchor: {
            width: 26,
            height: 48,
          },
        },
      }, // 起点图标配置
      endMark: {}, // 终点
      endMarkIcon: {
        url: endPoint,
        size: { width: 52, height: 52 },
        opts: { anchor: { width: 26, height: 48 } },
      },
      restaurants: [],
      path: [],
      play: false,
    };
  },
  watch: {},

  mounted() {
    // for (let i = 0; i < 30; i++) {
    //   const position = {lng: Math.random() * 40 + 85, lat: Math.random() * 30 + 21}
    //   this.markers.push(position)
    // }
    this.getScenic()
    this.getWeather()
    setTimeout(() => {
      this.maxZoom();
    }, 100);
    this.getCurrentTime();
    // this.getScenic()
    // this.routePoints()
  },

  methods: {
    getScenic() {
      crudScenic.getAll().then(res => {
        res.content.forEach(point => {
           const position = {lng: point.gisx, lat: point.gisy}
            this.markers.push(position)
            this.addOverlay(point)
            console.log(this.markers)

        })
      })
    },
    addOverlay(row) {
      if (row) {
        var point = new BMap.Point(row.gisx, row.gisy)
        var marker = new BMap.Marker(point)

        var opts = { width: 200,
          height: 100,
          enableMessage: false,
          message: 'ddd'
        }
        var infoWindow = new BMap.InfoWindow('测点：'  + '<br>', opts)
        marker.addEventListener('mouseover', function() {
          this.map.openInfoWindow(infoWindow, point) // 开启信息窗口
        })
        marker.addEventListener('click', function() {
          this.map.openInfoWindow(infoWindow, point) // 开启信息窗口
        })

        this.map.addOverlay(marker)
      }
    },
    reset() {

      this.play = !this.play;
    },
    //两点间的路线以及距离
    routePoints() {
      this.path = [];
      this.play = true;
      getAllRoutePoint().then((res) => {
        res.forEach((res) => {
          if (res.route_id === 1) {
            this.path.push(new this.BMap.Point(res.lng, res.lat));
          }
        });
        this.startMark = this.path[0]; // 起点
        this.endMark = this.path[this.path.length - 1]; // 终点
        console.log(this.startMark)
         console.log((this.map.getDistance(this.startMark,this.endMark)/1000).toFixed(2)+'米')

      });

      console.log(this.startMark);
    },
    maxZoom() {
      if (!screenfull.enabled) {
        this.$message({
          message: "you browser can not work",
          type: "warning",
        });
        return false;
      }
      if (!screenfull.isFullscreen) {
        screenfull.toggle();
      }
    },
    getCurrentTime() {
      var aData = new Date();
      const wk = aData.getDay();
      const weeks = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
      ];
      const week = weeks[wk];
      this.dateValue =
        aData.getFullYear() +
        "年" +
        (aData.getMonth() + 1) +
        "月" +
        aData.getDate() +
        "日&nbsp;&nbsp;&nbsp;" +
        week;
    },
    getWeather() {
      var that = this;
      this.$axios
        .get("http://api.openweathermap.org/data/2.5/weather?q=jincheng&appid=774c1e39382e4e4b89b4f5609186a0bb&lang=zh_cn")
        .then(function (reponse) {
          console.log(reponse)
          var data = reponse.data.main;
          // console.log(data.ganmao)
          that.content = reponse.data.weather[0].icon;
          that.weatherValue =  "天气：" +
            reponse.data.weather[0].description +
            // data.forecast[0].type +
            "&nbsp;&nbsp;&nbsp;" +
            parseFloat((data.temp-272.15).toFixed(1)) +
            " ℃";
        })
        .catch(() => {});
    },

    //根据名字得到地点坐标
    searchPointByName(name) {
      var ac = new BMap.Autocomplete({
        // 输入框的id
        input: name,
        location: this.map,
      });
      ac.addEventListener("onhighlight", function (e) {
        //鼠标放在下拉列表上的事件
      });
      var that = this;
      ac.addEventListener("onconfirm", function (e) {
        //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        // 拼装的地址信息
        var myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        that.setPlace(myValue);
        // console.log(that.setPlace(myValue))
      });
    },
    //添加城市控件
    addCityControl(map) {
      const cityControl = new BMap.CityListControl({
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        offset: new BMap.Size(10, 5),
      });
      map.addControl(cityControl);
    },
    //添加路线规划    1.WalkingRoute 步行规划    2.DrivingRoute 驾车路线规划
    addWalkRouting(start, end) {
      var walking = new BMap.WalkingRoute(this.map, {
        renderOptions: {
          map: this.map,
          /*
           * 这里是百度地图的检索路线结果面板，在html中写一个div用于展示，panel的值为div的id。
           * 有些时候我们可能不需要过多的信息，这时可以用onSearchComplete方法自定义一个面板。
           */
          panel: "r-result",
          // 是否选择第一个检索结果
          selectFirstResult: true,
          // 检索结束后是否自动调整地图视野
          autoViewport: true,
        },
        // 检索完成后回调
        onSearchComplete: function (results) {
          if (walking.getStatus() != BMAP_STATUS_SUCCESS) {
            return;
          }
          // 获取第一个路线
          var plan = results.getPlan(0);
          // 获取时间
          plan.getDuration(true);
          // 获取距离
          plan.getDistance(true);
        },
      });
      var start = new BMap.Point(112.86019, 35.55622);
      var end = new BMap.Point(112.848176, 35.494466);
      walking.search(start, end);
    },
    handler({ BMap, map }) {
      this.BMap = BMap;
      console.log(BMap);
      this.map = map;
      this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      this.map.addControl(new BMap.NavigationControl()); // 添加平移缩放控件
      this.map.addControl(new BMap.ScaleControl()); // 添加比例尺控件
      this.map.addControl(new BMap.OverviewMapControl()); // 添加缩略地图控件
      point = new BMap.Point(this.lng, this.lat);
      this.map.centerAndZoom(point, 16);

      this.marker = new BMap.Marker(point); // 创建标注
      this.map.addOverlay(this.marker); // 将标注添加到地图中
      this.circle = new BMap.Circle(point, 6, {
        strokeColor: "Red",
        strokeWeight: 6,
        strokeOpacity: 1,
        Color: "Red",
        fillColor: "#f03",
      });
      this.map.addOverlay(this.circle);
      // this.map.setHeading(64.5);   //设置地图旋转角度
      // this.map.setTilt(73);       //设置地图的倾斜角度
      // this.map.setMapType(BMAP_EARTH_MAP);
      // this.map.setHeading(64.5)
      this.searchPointByName("suggestId");
      this.searchPointByName("start");
      this.searchPointByName("end");
      this.addCityControl(this.map);
    },
    setPlace(e) {
      var point = {};
      const self = this;
      this.map.clearOverlays(); //清除地图上所有覆盖物
      // 创建一个检索对象
      var local = new BMap.LocalSearch(self.map, {
        //智能搜索
        onSearchComplete: function () {
          var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          // 获取的经纬度根据自己业务赋值
          point = pp;
          self.lng = pp.lng;
          self.lat = pp.lat;
          self.map.centerAndZoom(pp, 18);
          self.map.addOverlay(new BMap.Marker(pp)); //添加标注
        },
      });
      local.search(e);
      console.log(local.search(e));
      return point;
    },
    //地图点击事件
    getClickInfo(e) {
      console.log(e.point.lng);
      console.log(e.point.lat);
    },
    search() {
      // this.$router.push("/index");
      var jd = document.getElementById("startAddress");
      var wd = document.getElementById("endAddress");
      this.lng = jd.value;
      this.lat = wd.value;
      if (jd.value !== "" && wd.value !== "") {
        point = new this.BMap.Point(this.lng, this.lat);
        this.map.centerAndZoom(point, 12);
        this.map.clearOverlays();
        var marker = new this.BMap.Marker(point); // 创建标注
        this.map.addOverlay(marker); // 将标注添加到地图中
        console.log(this.BMap);
      } else {
        if (jd.value == "" && wd.value == "") {
          alert("请输入经纬度");
        } else if (jd.value == "") {
          alert("请输入经度");
        } else if (wd.value == "") {
          {
            alert("请输入维度");
          }
        }
      }
    },
    route() {
      this.map.clearOverlays();
      console.log(this.routes[0]);
      var marker1 = new this.BMap.Marker(this.routes[0]);
      var marker3 = new this.BMap.Marker(this.routes[this.routes.length - 1]);

      /*添加文字标注*/
      var label1 = new BMap.Label("起点", {
        position: this.routes[0],
        offset: new BMap.Size(1, 2),
      });
      var label2 = new BMap.Label("终点", {
        position: this.routes[this.routes.length - 1],
        offset: new BMap.Size(1, 2),
      });
      this.map.addOverlay(label1);
      this.map.addOverlay(label2);
      this.map.addOverlay(marker1);
      this.map.addOverlay(marker3);

      var polyline = new this.BMap.Polyline(this.routes, {
        strokeColor: "blue",
        strokeWeight: 6,
        strokeOpacity: 0.5,
      });
      console.log(Math.ceil(this.routes.length / 2));
      this.map.centerAndZoom(
        this.routes[Math.ceil(this.routes.length / 2)],
        16
      );
      console.log(this.routes);
      this.map.addOverlay(polyline);
      console.log(this.BMap.Polyline);
    },
    /*通过下拉框检索的相关方法*/
    // getSearchPoint(data) {
    //   this.map.clearOverlays();
    //   // this.map.removeOverlay(this.maker);
    //   // this.map.removeOverlay(this.circle);
    //   this.place = data.title;
    //   this.point = new BMap.Point(data.point.lng, data.point.lat);
    //   console.log(this.point);
    //   this.map.centerAndZoom(this.point, 16);
    //   this.marker = new BMap.Marker(this.point);
    //   this.map.addOverlay(this.marker);

    // },
    // remoteMethod(query) {
    //   if (query !== "") {
    //     this.loading = true;
    //     setTimeout(() => {
    //       this.loading = false;
    //       this.searchPlace(query);
    //     }, 200);
    //   } else {
    //     this.restaurants = [];
    //   }
    // },
    // searchPlace(place) {
    //   var ls = new BMap.LocalSearch(this.city);
    //   ls.search(place);
    //   var that = this;
    //   this.path = [];
    //   ls.setSearchCompleteCallback(function (searchResult) {
    //     if (ls.getStatus() == BMAP_STATUS_SUCCESS) {
    //       that.restaurants = searchResult.Yr;
    //       console.log(that.restaurants);
    //     } else {
    //       console.log("查无此地");
    //       return;
    //     }
    //   });
    // },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}

.el-menu-item.is-active {
  background-color: #3370ff !important;
  color: #fff;
  span {
    color: #fff !important;
  }
}
</style>

